<template>
  <van-uploader
    :after-read="afterRead"
    :before-read="beforeRead"
    reupload
    :accept="accept"
    :max-count="limit"
    :max-size="maxSize"
    :disabled="loading"
  >
    <van-button
      icon="plus"
      color="linear-gradient(to right, #ff6034, #ee0a24)"
      size="small"
      :loading="loading"
      loading-text="上传中..."
      >上传文件</van-button
    >
  </van-uploader>

  <div v-for="(item, index) of uploadList" :key="index" class="file-item">
    <a :href="item" target="_blank">点击查看</a>
    <span class="delete-btn" @click="deleteItem(item)">X</span>
  </div>
  <div class="tips">
    <h3>图片/附件要求</h3>
    <h4>
      上传完善好的附件，支持上传文件<span>{{ accept }}</span>
    </h4>
  </div>
</template>

<script setup lang="ts" name="ImageUpload">
import { computed, ref, watch } from "vue";
import { http } from "@/utils/http";
import { showFailToast, showSuccessToast } from "vant";

const props = defineProps({
  fileList: {
    type: Array,
    default: [] as any[]
  },
  limit: {
    type: Number,
    default: 5
  },
  max: {
    type: Number,
    default: 5
  },
  accept: {
    type: String,
    default: ".pdf,.ppt,.pptx"
  }
});
const emits = defineEmits(["success"]);
const uploadList = ref<string[]>([]);
const maxSize = computed(() => props.max * 1024 * 1024);
const loading = ref(false);

function afterRead(file: any) {
  loading.value = true;
  const data = new FormData();
  data.append("file", file.file);
  // 此时可以自行将文件上传至服务器
  http
    .request({ url: "/resource/oss/upload", method: "post", data })
    .then((res: any) => {
      uploadList.value.push(res.data.url);

      emits("success", uploadList.value);
      showSuccessToast("上传成功");
    })
    .finally(() => (loading.value = false));
}

function beforeRead(file: any) {
  const arr = file.name.split(".");
  const type = arr[arr.length - 1];
  const acceptTypes = props.accept.split(",");
  if (!acceptTypes.includes("." + type)) {
    showFailToast("请上传" + props.accept + "格式");
    return false;
  }
  if (file.size > maxSize.value) {
    showFailToast("文件大小不能超过" + props.max + "MB");
    return false;
  }
  return true;
}

function deleteItem(item: string) {
  uploadList.value = uploadList.value.filter(i => i !== item);
  emits("success", uploadList.value);
}

watch(
  () => props.fileList,
  (val: any[]) => {
    uploadList.value = val;
  }
);
</script>

<style scoped lang="less">
.file-item {
  width: 100%;
  font-size: 0.9rem;
  word-break: break-all;
  margin-top: 0.6rem;

  .delete-btn {
    margin-right: 0.4rem;
    float: right;
    color: #ff4350;
  }
}
.tips {
  margin-top: 1rem;
  font-size: 0.9rem;

  span {
    margin: 0 0.2rem;
    color: #ff4350;
  }
}
</style>
